package com.zhihao.takeaway.common.elasticsearchStudy;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

// 业务编写
@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

//    不能直接使用 Autowird 需要启动spring容器
    public static void main(String[] args)throws Exception{
        new ContentService().parseContent("java");
    }
//    1、解析数据放入es索引中
    public Boolean parseContent(String keywords)throws Exception{
        List<ElasticSearchTestContent> elasticSearchTestContents = new HtmlParseUtil().parseJD(keywords);
//        把查询到的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for(int i = 0 ; i < elasticSearchTestContents.size() ; i++){
            System.out.println(JSON.toJSONString(elasticSearchTestContents.get(i)));
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(elasticSearchTestContents.get(i)), XContentType.JSON));
        }
        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulkItemResponses.hasFailures();
    }
//    2、获取数据，实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize)throws Exception{
        if(pageNo<=0){
            pageNo = 1;
        }
//        条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

//        分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

//        精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

//        高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

//        执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        解析结果

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for(SearchHit documentFields : search.getHits().getHits()){
//            解析高亮字段
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
//            把所有的标题获取出来（高亮字段的标题）
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();  // 原来的未高亮的字段
//            解析高亮字段
//            把高亮字段替换为原来没有高亮的字段
//            这一步是取出高亮字段
            if(title != null){
                Text[] fragments = title.fragments();
//                新的标题
                String n_title = "";
                for(Text text:fragments){
                    n_title += text;
                }
                sourceAsMap.put("title",n_title); // 高亮字段替换掉原来的内容即可

            }
            list.add(sourceAsMap);
//            非高亮一步保存即可
            //            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }
}
